// pages/case/upload/index.js
var api = require('../../../utils/serve')
var moment = require('moment');
import  tool from "../../../utils/tool"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',//姓名
    sex: '',//性别
    age: '',//年龄
    province: '',//省份
    nurseTime: '',//调理时间
    goods: '',//使用商品
    useBefore: '',//调理前感受
    useAfter: '',//调理后感受
    fileList: [],
    show: false,//商品弹窗
    nurseShow: false,//调理时间弹窗
    userId: "",
    fileName: '',
    ossList: '',
    imagePathList: [],
    imagePathList2: [],
    urlName1: [],
    urlName2: [],
    districtList: [], //省份下拉表
    provinceData: [],//省份数据
    districtListShow: false,//省份弹窗
    //调理前标签数据
    beforeTagData: [],
    //调理后标签数据
    afterTagData: [],
    //商品数据
    list: [],
    selectedGoods: [],
    startTime: '',//开始时间
    endTime: '',//结束时间
    timeSelet: 1,
    currentDate: new Date().getTime(),
    // minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      return value;
    },
    timeList: [{
      id: 0,
      num: 0,
      time: '周一',
      checked: false
    },

    {
      id: 1,
      num: 0,
      time: '周二',
      checked: false
    },
    {
      id: 2,
      num: 0,
      time: '周三',
      checked: false
    },

    {
      id: 3,
      num: 0,
      time: '周四',
      checked: false
    },
    {
      id: 4,
      num: 0,
      time: '周五',
      checked: false
    },
    {
      id: 5,
      num: 0,
      time: '周六',
      checked: false
    },
    {
      id: 6,
      num: 0,
      time: '周末',
      checked: false
    },
    ],
   
    timeColumns: ['三个月', '半年', '一年'],
    timeValue: '三个月',
    allCount: '',
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.userId = wx.getStorageSync('userId')
  },
  //选择开始时间
  changeTimeSelect() {
    this.setData({
      timeSelet: 1
    })
  },
  //选择结束时间
  changeTimeSelect2() {
    this.setData({
      minDate: moment(this.data.startTime).format('x'),
      timeSelet: 2
    })
  },
  //时间输入框
  onInput(event) {
    if (this.data.timeSelet === 1) {
      this.setData({
        startTime: moment(event.detail).format("YYYY-MM-DD"),
      });
    } else {
      this.setData({
        endTime: moment(event.detail).format("YYYY-MM-DD"),
      });
    }
    this.setData({
      currentDate: event.detail,
    });
  },
  //吸灸打卡 
  punchHandle() {
    api.get('/zkxj/user/conditioning/clock', {
      userId: this.data.userId
    }).then(res => {
      if (res.data.code === 0) {
        this.getCount()
        this.getCountAll()
      }
    })
  },

  // 选择时间提交事件
  handleNurseSubmit() {
    this.setData({
      nurseTime: this.data.startTime + '~' + this.data.endTime,
      nurseShow: false
    })

  },
  //商品提交事件
  handleGoodsSubmit() {
    const arr = []
    const ids = []
    this.data.list.forEach(i => {
      i.goodList.forEach(k => {
        if (k.selected) {
          arr.push(k.goodName)
          ids.push(k.goodId)
        }
      })
    })
    console.log(ids.join(','));
    this.setData({
      goods: arr.join(','),
      selectedGoods: ids.join(','),
      show: false

    })

  },
  //选择商品事件
  handleGoodsChange(e) {

    const id = e.currentTarget.dataset.id
    let first = 0
    let second = 0
    this.data.list.forEach((i, index) => {
      i.goodList.forEach((k, idx) => {
        if (k.goodId === id) {
          first = index
          second = idx
        }
      })
    })
    this.setData({
      ["list[" + first + "].goodList[" + second + "].selected"]: !this.data.list[first].goodList[second].selected
    })
  },
  //调理前标签点击事件 
  handleBeforeTagChange(e) {
    const idx = e.currentTarget.dataset.idx
    this.setData({
      ["beforeTagData[" + idx + "].selected"]: !this.data.beforeTagData[idx].selected
    })
  },
  //调理后标签点击事件
  handleAfterTagChange(e) {
    const idx = e.currentTarget.dataset.idx
    this.setData({
      ["afterTagData[" + idx + "].selected"]: !this.data.afterTagData[idx].selected
    })
  },
  //显示商品弹窗
  onClickIcon() {
    this.setData({
      show: true
    })
  },
  //商品弹窗关闭
  onClose() {
    this.setData({
      show: false,
    });
  },
  //选择时间弹窗关闭
  onCloseNurse() {
    this.setData({
      nurseShow: false,
    });
  },
  //取消商品按钮
  cancelPopup() {
    this.setData({ show: false, });
  },
  //取消选择时间按钮
  cancelPopupNurse() {
    this.setData({ nurseShow: false, });
  },
  //获取使用前输入框文本框值
  onChangeBefore(event) {
    this.setData({
      useBefore: event.detail
    })
  },
  //获取使用后输入框文本框值
  onChangeAfter(event) {
    this.setData({
      useAfter: event.detail
    })
  },
  //取消省份选择框
  cancelDistrict() {
    this.setData({
      districtListShow: false
    })
  },
  clickIconProvince() {
    this.setData({
      districtListShow: true
    })
  },
  onClickIconNurse() {
    this.setData({
      nurseShow: true
    })
  },

  //省份选择框确定事件
  confirmDistrict(e) {
    const { picker, value, index } = e.detail;
    this.setData({
      province: value,
      districtListShow: false
    })
  },
  onCloseTime() {
    this.setData({
      nurseShow: false
    })
  },
  timeOnchange(event) {
    const { picker, value, index } = event.detail
    this.setData({
      timeValue: value
    })

  },
  //确定选择时间段 
  timeSubmit() {
    this.setData({
      nurseTime: this.data.timeValue,
      nurseShow: false

    })
  },
  //确定上传 
  submit() {
    const key = moment(new Date()).format("YYYY-MM-DD");
    const arr = []
    const arr1 = []
    this.data.urlName1.map((i) => {
      i = key + '/' + i
      arr.push(i)
    })
    this.data.urlName2.map((i) => {
      i = key + '/' + i
      arr1.push(i)
    })
    const beforeData = []
    const afterTagData = []
    const arrData = []
    const arrData1 = []
    this.data.beforeTagData.forEach(i => {
      if (i.selected) {
        beforeData.push(i.keyword)
        arrData.push(i.id)
      }
    })
    this.data.afterTagData.forEach(i => {
      if (i.selected) {
        afterTagData.push(i.keyword)
        arrData1.push(i.id)
      }
    })
      api.post('/zkxj/user/feedback/add', {
        goodIds: this.data.selectedGoods,
        useAfter: afterTagData.join(',') + ',' + this.data.useAfter,
        useBefore: beforeData.join(',') + ',' + this.data.useBefore,
        userAfterPics: arr1,
        userBeforePics: arr,
        useBeforeIdList:arrData,
        useAfterIdList:arrData1,
        userId: this.data.userId,
        province: this.data.province,
        useTime:this.data.nurseTime
      }).then((res) => {
        if (res.data.code === 0) {
          wx.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 1000,
            mask: true
          })
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/case/caseList/index',
            })
          }, 2000)
        }
      })
   
  },
  noop() { },
  //使用前图片上传
  chooseImg1() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const data = res.tempFiles
        that.setFile(data)

        that.getOssKeyword(data[0].fileName, data[0].tempFilePath)
        const arr = []
        const arr1 = []
        data.map((i) => {
          arr.push(i.fileName)
          arr1.push(i.tempFilePath)
        })
        that.setData({
          urlName1: [...that.data.urlName1, ...arr],
          imagePathList: [...that.data.imagePathList, ...arr1]
        })

      }
    })
  },
  handleCancle(e) {
    const idx = e.currentTarget.dataset.idx
    this.data.imagePathList.splice(idx, 1);
    this.data.urlName1.splice(idx, 1)
    this.setData({
      urlName1: this.data.urlName1,
      imagePathList: this.data.imagePathList
    })

  },
  handleCancle2(e) {
    const idx = e.currentTarget.dataset.idx
    this.data.imagePathList2.splice(idx, 1);
    this.data.urlName2.splice(idx, 1)
    this.setData({
      urlName2: this.data.urlName2,
      imagePathList2: this.data.imagePathList2
    })

  },
  //使用后图片上传
  chooseImg2() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const data = res.tempFiles
        that.setFile(data)
        that.getOssKeyword(data[0].fileName, data[0].tempFilePath)
        const arr = []
        const arr1 = []
        data.map((i) => {
          arr.push(i.fileName)
          arr1.push(i.tempFilePath)
        })
        that.setData({
          urlName2: [...that.data.urlName2, ...arr],
          imagePathList2: [...that.data.imagePathList2, ...arr1]
        })

      }
    })
  },
  //随机生成文件名 
  setFile(data) {
    // 将wx.chooseImage返回的数据进行扩展
    data.map((item, index) => {
      // 通过路径截取文件后缀名
      const fileFormat = item.tempFilePath.substring(item.tempFilePath.lastIndexOf(".") + 1, item.tempFilePath.length);
      // wx.getFileSystemManager()小程序文件管理器api，可以将通过文件路径将其转换成64编码
      //   const fileManager = wx.getFileSystemManager();
      //   const base64 = fileManager.readFileSync(item.tempFilePath, 'base64');
      //   item.fileContent = base64;
      //   item.fileSize = item.size;
      // 通过时间获取随机13位随机数并且拼接文件后缀进行文件命名
      item.fileName = this.getFileName(13) + '.' + fileFormat;
      // 此处操作是用来进行选中图片显示的，只有这样拼接才能显示base64编码的路径
      // item.tempFilePath = `data:image/${fileFormat};base64,${base64}`;;

    })
    this.setData({
      // imagePathList: this.data.imagePathList.concat(dtempFilePath)
    });
    // 此处操作是用来将获取到的文件数据传递给父组件进行文件上传
    // this.triggerEvent('imageChange', this.data.fileList)
  },
  // 随机生成文件名
  getFileName(m) {
    m = m > 13 ? 13 : m;
    var num = new Date().getTime();
    return num.toString().substring(13 - m);
  },


  // 获取oss参数
  getOssKeyword(name, path) {
    // console.log(path)
    const key = moment(new Date()).format("YYYY-MM-DD");
    api.get('/zkxj/basic/oss', {
      dir: key,
      filename: name
    }).then(res => {
      if (res.data.code === 0) {
        this.setData({ ossList: res.data.data })
        wx.uploadFile({
          url: 'https://oss.zhongkexiangjiu.cn/',
          filePath: path,
          name: 'file', // 必须填file。
          formData: {
            key: this.data.ossList.key,
            policy: this.data.ossList.policy,
            OSSAccessKeyId: this.data.ossList.accessId,
            signature: this.data.ossList.signature,

          },
          success: (res) => {
            if (res.statusCode === 204) {
              console.log('上传成功');
            }
          },
          fail: err => {
            console.log(err);
            wx.showToast({
              title: '上传失败，请重新上传',
              icon: 'error',
              duration: 1000,
              mask: true
            })
          }
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getList()
    this.getDistrict()
    this.getKeyList()
    this.getUser()
    this.getCount()
    this.getCountAll()
    // tool.throttle(this.punchHandle(),300)
  },
  //请求商品数据接口
  getList() {
    api.get('/zkxj/good/categoryList').then(res => {
      if (res.data.code === 0) {
        this.setData({ list: res.data.data })
      }
    })
  },
  //获取当前一周的调理次数统计 
  getCount() {
    let list = this.data.timeList
    api.get('/zkxj/user/conditioning/week/count', {
      userId: this.data.userId
    }).then(res => {
      if (res.data.code === 0) {
        list.forEach((item, index) => {
          res.data.data.forEach(i => {
            if (index === i.dayOfWeek - 1) {
              item.num = i.countNum
              if (i.countNum !== 0) {
                item.checked = true
              }
            }
          })
        })
        this.setData({ timeList: list })
      }
    })
  },
  //吸灸累计总数
  getCountAll() {
    api.get('/zkxj/user/conditioning/count', {
      userId: this.data.userId
    }).then(res => {
      if (res.data.code === 0) {
        this.setData({ allCount: res.data.data })
      }
    })
  },
  //请求省份下拉框
  getDistrict() {
    const districtParam = {
      parentId: 1
    }
    api.post('/zkxj/basic/district/list', districtParam).then(res => {
      if (res.data.code === 0) {
        let data = []
        res.data.data.forEach(i => {
          data.push(i.name)
        })
        this.setData({ districtList: data, provinceData: res.data.data })
      }
    })
  },
  //获取用户信息
  getUser() {
    api.get('/zkxj/user/getUserCardInfo', {
      userId: this.data.userId
    }).then(res => {
      if (res.data.code === 0) {
        this.setData({
          name: res.data.data.realName,
          sex: res.data.data.gender,
          age: res.data.data.age
        })
      }
    })
  },
  //请求关键词列表
  getKeyList() {
    api.get('/zkxj/basic/getKeywordList', {
      type: 1
    }).then(res => {
      if (res.data.code === 0) {
        this.setData({ beforeTagData: res.data.data })
      }
    })
    api.get('/zkxj/basic/getKeywordList', {
      type: 2
    }).then(res => {
      if (res.data.code === 0) {
        this.setData({ afterTagData: res.data.data })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})